<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：100条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button
                type="warning"
                size="small"
                @click="$router.push('/import')"
              >
                导入excel
              </el-button>
              <el-button
                type="danger"
                size="small"
                :loading="downloadLoading"
                @click="exportData"
              >
                导出excel
              </el-button>
              <el-button type="primary" size="small" @click="showDialog = true">
                新增员工
              </el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table
            border
            :data="employeesList"
            :default-sort="{ prop: 'workNumber', order: 'descending' }"
          >
            <el-table-column label="序号" type="index" />
            <el-table-column label="姓名" prop="username" />
            <el-table-column label="头像">
              <template #default="{ row }">
                <img
                  :src="row.staffPhoto"
                  style="width: 100px; height: 100px; border-radius: 50%"
                  @click="showErweima(row.staffPhoto)"
                />
              </template>
            </el-table-column>

            <el-table-column label="工号" prop="workNumber" sortable />
            <el-table-column label="聘用形式" prop="formOfEmployment">
              <template #default="{ row }">
                {{ hire(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column label="部门" prop="departmentName" />
            <el-table-column label="入职时间" prop="correctionTime" />
            <el-table-column label="账户状态">
              <el-switch v-model="qs" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{ row }">
                <el-button type="text" size="small" @click="getDetail(row.id)">
                  查看
                </el-button>
                <el-button type="text" size="small" @click="assignRole">
                  分配角色
                </el-button>
                <el-button type="text" size="small">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination
              layout="prev, pager, next,sizes"
              :total="total"
              :current-page="params.page"
              :page-sizes="[10, 5, 15, 20]"
              :page-size="params.size"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </el-row>
        </div>
      </el-card>
    </div>
    <el-dialog
      title="头像二维码"
      :visible="showerweima"
      width="15%"
      @close="showerweima = false"
    >
      <canvas ref="myCanvas" />
    </el-dialog>
    <assign-role :showassignrole.sync="showassignrole" />
  </div>
</template>
<script>
import qrcode from 'qrcode'
import { getEmployeeList } from '@/api/employees'
import EnumType from '@/api/constant/employees'
import AssignRole from './components/assign-role.vue'
console.log(EnumType.hireType)
export default {
  components: { AssignRole },
  data () {
    return {
      showassignrole: false,
      showerweima: false,
      showDialog: false,
      downloadLoading: false,
      EnumType,
      qs: true,
      params: { page: 1, size: 10 },
      employeesList: [],
      total: 0
    }
  },
  created () {
    this.getEmployees()
  },
  methods: {
    assignRole () {
      this.showassignrole = true
    },
    showErweima (imgurl) {
      this.showerweima = true
      console.log(imgurl)
      this.$nextTick(() => {
        qrcode.toCanvas(this.$refs.myCanvas, imgurl)
      })
    },
    getDetail (id) {
      console.log(id)
      this.$router.push(`/employees/detail/${id}`)
    },
    async exportData () {
      // 1. 开始导出
      this.downloadLoading = true
      // 2. 使用Excel导出插件导出数据（核心）
      // import('@/utils/Export2Excel') 按需加载一个js模块（懒加载）
      const excel = await import('@/vender/Export2Excel')
      console.log('excel导出方法：', excel)
      const userheader = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '工号': 'workNumber',
        '转正日期': 'correctionTime',
        '部门': 'departmentName'
      }
      const header = Object.keys(userheader) // 导出数据的表头
      const enheader = Object.values(userheader)

      const data = this.transfromListtoArr(this.employeesList, enheader)
      console.log(data)
      excel.export_json_to_excel({
        // 表头 必填
        header,

        // 表头对应的具体数据 必填
        data,
        filename: `elm-list-${Date.now()}`, // 导出下载的文件名称
        autoWidth: true, // 导出excel列宽度是否自适应
        bookType: 'xlsx' // 导出生成的文件类型
      })
      // 3. 导出成功关闭loading
      this.downloadLoading = false
    },
    transfromListtoArr (list, enheader) {
      const arr = []
      list.forEach(item => {
        const newarr2 = []
        for (const key in item) {
          if (enheader.includes(key)) {
            if (key === 'formOfEmployment') {
              newarr2.push(this.hire(item[key]))
              continue
            }
            newarr2.push(item[key])
          }
        }
        arr.push(newarr2)
      })
      return arr
    },
    hire (type) {
      const map = {}
      this.EnumType.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[type]
    },
    handleCurrentChange (page) {
      this.params.page = page
      this.getEmployees()
    },
    handleSizeChange (size) {
      this.params.size = size
      this.getEmployees()
    },
    async getEmployees () {
      try {
        const res = await getEmployeeList(this.params)
        this.employeesList = res.rows
        this.total = res.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.el-dialog__body {
  canvas {
    display: block;
    margin: 0 auto;
  }
}
</style>
